#pragma once

#include <string>
#include <fstream>

class Util
{
public:

    /// @brief 根据step分割为一行
    /// @param inbuffer 输入流字符参数
    /// @param step 分割字符
    /// @return 返回切割好的一行
    static std::string getline(std::string &inbuffer, const std::string& step)
    {
        auto pos = inbuffer.find(step);
        if (pos == std::string::npos)
        {
#ifdef DEBUG
            std::cout << "getline 为空" << std::endl;
#endif
            return "";
        }

        std::string ret = inbuffer.substr(0, pos);
        inbuffer.erase(0, ret.size() + step.size());
        return ret;
    }

    /// @brief 获取文件内容
    /// @param filepath 文件路径
    /// @param out 读取到的内容
    /// @return 成功返回true，失败返回false
    static bool readFile(const std::string& filepath, std::string* out)
    {
        std::ifstream infile(filepath, std::ifstream::in);
        if (!infile.is_open())
        {
            return false;
        }

        infile.seekg (0, infile.end);
        int length = infile.tellg();
        infile.seekg (0, infile.beg);
        char * buffer = new char [length];

        infile.read(buffer, length);
        // std::string read;
        // while (infile >> read)
        // {
        //     *out += read;
        // }
        *out = buffer;

        infile.close();
        delete[] buffer;
        return true;
    }

    /// @brief 根据后缀转换 Content-Type
    /// @param suffix 后缀
    /// @return 转换后的 Content-Type
    static std::string suffixToDoec(const std::string& suffix)
    {
        // string respheader = "Content-Type: text/html\r\n";
        std::string doec = "Content-Type: ";
        if (suffix == ".html")
            doec += "text/html";
        else if (suffix == ".jpg")
            doec += "image/jpeg;application/x-jpg";

        doec += "\r\n";
        return doec;
    }
};